#include <psp2/io/stat.h>

#include "scec2c.h"
#include "config.h"
#include "utils.h"
#include "main.h"
#include "menu.h"

const char *error_texts[] = {
    "无错误",
    "配置加载完成",
    "配置加载出错！",
    "配置保存完成",
    "配置保存出错！",
};

SettingConfig setting_config;
int config_error_code = CONFIG_ERROR_CODE_NO_ERROR;

int resetConfig()
{
    memset(&setting_config, 0, sizeof(SettingConfig));
    setting_config.version = SETTING_CONFIG_VERSION;
    updateMenuOptions();
    return 0;
}

int loadConfigEx(int type)
{
    SettingConfig temp;
    char path[MAX_PATH_LENGTH];

    if (type == CONFIG_TYPE_CURRENT)
        snprintf(path, MAX_PATH_LENGTH, "%s/%s.bin", CONFIG_DIR, g_titleid);
    else
        snprintf(path, MAX_PATH_LENGTH, "%s/default.bin", CONFIG_DIR);

    int ret = ReadFile(path, &temp, sizeof(SettingConfig));
    if (ret < 0 || ret != sizeof(SettingConfig) || temp.version != SETTING_CONFIG_VERSION)
    {
        if (type == CONFIG_TYPE_CURRENT)
            loadConfigEx(CONFIG_TYPE_DEFAULT);
        else
            resetConfig();
        return CONFIG_ERROR_CODE_LOAD_ERROR;
    }
    memcpy(&setting_config, &temp, sizeof(SettingConfig));
    updateMenuOptions();

    return CONFIG_ERROR_CODE_LOAD_OK;
}

int saveConfigEx(int type)
{
    char path[MAX_PATH_LENGTH];

    sceIoMkdir(DATA_DIR, 0777);
    sceIoMkdir(CONFIG_DIR, 0777);

    if (type == CONFIG_TYPE_CURRENT)
        snprintf(path, MAX_PATH_LENGTH, "%s/%s.bin", CONFIG_DIR, g_titleid);
    else
        snprintf(path, MAX_PATH_LENGTH, "%s/default.bin", CONFIG_DIR);

    int ret = WriteFile(path, &setting_config, sizeof(SettingConfig));
    if (ret != sizeof(SettingConfig))
        return CONFIG_ERROR_CODE_SAVE_ERROR;

    return CONFIG_ERROR_CODE_SAVE_OK;
}

int loadConfig()
{
    return loadConfigEx(CONFIG_TYPE_CURRENT);
}

int saveConfig()
{
    return saveConfigEx(CONFIG_TYPE_CURRENT);
}